package com.lollipop.programming.thread.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SemaphoreDemo {
    public static void main(String[] args) {
        // 创建Semaphore，许可数为2
        Semaphore semaphore = new Semaphore(2);

        // 创建5个线程
        for (int i = 1; i <= 5; i++) {
            final int threadId = i;
            new Thread(() -> {
                try {
                    log.info("线程 {} 尝试获取许可", threadId);
                    // 获取许可
                    semaphore.acquire();
                    log.info("线程 {} 获取到许可，开始执行", threadId);

                    TimeUnit.SECONDS.sleep(2);
                    log.info("线程 {} 执行完成，释放许可", threadId);
                } catch (InterruptedException e) {
                    log.error("线程 {} 执行过程中被中断", threadId);
                } finally {
                    // 释放许可
                    semaphore.release();
                }
            }).start();
        }
    }
}